import DomUtil from "./dom";
const { on, off } = DomUtil;
export interface ResizeTask {
  id: Number;
  resize: Function;
}
let debounceInter: any = -1;
const debounceWait = 200;
const tasks: ResizeTask[] = [];
const handler = function () {
  clearTimeout(debounceInter);
  debounceInter = setTimeout(() => {
    console.log("resize");
    tasks.forEach((task) => {
      task.resize();
    });
  }, debounceWait);
};
let id = 0;
export default {
  add(fn: Function, immediate?: boolean) {
    id++;
    if (tasks.length === 0) {
      on(window, "resize", handler);
    }
    tasks.push({
      id,
      resize: fn,
    });
    if (immediate) {
      fn();
    }
    console.log("resizer add", tasks.length);
    return id;
  },
  remove(id: number) {
    tasks.forEach((task, i) => {
      if (task.id === id) {
        tasks.splice(i, 1);
        return false;
      }
    });
    console.log("resizer remove", tasks.length);
    if (tasks.length === 0) {
      off(window, "resize", handler);
    }
  },
};
